/*
 * Copyright 2002-2007 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.services;

import javax.annotation.security.RolesAllowed;
import org.internna.iwebjtracker.administration.PollManager;
import org.internna.iwebmvc.dao.DAO;
import org.internna.iwebmvc.model.Poll;
import org.internna.iwebmvc.model.UUID;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebmvc.parsers.PollParser;
import org.internna.iwebjtracker.i18n.MessageResolver;
import org.internna.iwebjtracker.project.validation.Errors;
import org.internna.iwebmvc.logging.Log4JRuntimeConfigurator;
import org.internna.iwebmvc.logging.Log4JRuntimeConfigurator.LOG_LEVEL;
import org.springframework.context.MessageSource;
import org.springframework.beans.factory.annotation.Required;

import static org.internna.iwebmvc.utils.StringUtils.hasText;
import static org.internna.iwebmvc.model.security.RoleImpl.ROLE_ADMINISTRATOR;

/**
 * Allows secured remote administration operations.
 *
 * @author Jose Noheda
 * @since 1.0
 */
public final class AJAXAdministrator extends MessageResolver implements Administrator {

    private DAO dao;
    private PollParser parser;
    private PollManager pollManager;
    private Log4JRuntimeConfigurator log4j;

    public AJAXAdministrator(MessageSource messageSource) {
        super(messageSource);
    }

    /**
     * Spring injection point (REQUIRED)
     *
     * @param dao a non null instance
     */
    @Required public void setDao(DAO dao) {
        Assert.notNull(dao);
        this.dao = dao;
    }

    /**
     * Spring injection point (REQUIRED)
     *
     * @param parser a non null instance
     */
    @Required public void setParser(PollParser parser) {
        Assert.notNull(parser);
        this.parser = parser;
    }

    /**
     * Spring injection point (REQUIRED)
     *
     * @param pollManager a non null instance
     */
    @Required public void setPollManager(PollManager pollManager) {
        Assert.notNull(pollManager);
        this.pollManager = pollManager;
    }

    /**
     * Setter for Spring dependency injection.
     *
     * @param log4j
     */
    @Required public void setLog4j(Log4JRuntimeConfigurator log4j) {
        Assert.notNull(log4j);
        this.log4j = log4j;
    }

    /**
     * Allows administrators to change the log4j configuration on real time. If
     * the level specified is not valid it defaults to DEBUG.
     *
     * @param logger any
     * @param level any
     */
    @RolesAllowed(ROLE_ADMINISTRATOR)
    @Override public void changeLoggerLevel(String logger, String levelIdentifier) {
        if (hasText(logger) && hasText(levelIdentifier)) {
            LOG_LEVEL level = LOG_LEVEL.from(levelIdentifier);
            log4j.changeLoggerLevel(logger, level, true);
        }
    }

    /**
     * Parses the poll and updates the database.
     *
     * @param poll any
     */
    @RolesAllowed(ROLE_ADMINISTRATOR)
    @Override public String managePoll(Poll poll, boolean activate) {
        Poll parsed = parser.parse(poll);
        if (parsed != null) {
            parsed.setActive(activate);
            if (parsed.getId() == null) {
                dao.create(parsed);
            } else {
                dao.update(parsed);
            }
            return null;
        }
        return resolve(Errors.MISSING_INFO);
    }

    /**
     * Changes the activation flag of a poll given its primary key.
     *
     * @param poll any
     */
    @RolesAllowed(ROLE_ADMINISTRATOR)
    @Override public String togglePoll(UUID id) {
        if (id != null) {
            Poll poll = dao.find(Poll.class, id);
            if (poll != null) {
                poll.setActive(!poll.isActive());
                dao.update(poll);
                return null;
            }
        }
        return resolve(Errors.MISSING_INFO);
    }

}
